package cn.lijiajia3515.cairo.auth.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurer;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.cache.interceptor.CacheResolver;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cache.interceptor.SimpleKeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.CacheKeyPrefix;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;


@Slf4j
@EnableCaching
@Configuration(proxyBeanMethods = false)
public class CacheConfig {

	@Bean
	public MyCustomCacheConfig myCustomCacheConfig(){
		return new MyCustomCacheConfig();
	}



	public static class MyCustomCacheConfig extends CachingConfigurerSupport {

		@Override
		public CacheManager cacheManager() {
			return null;
		}

		@Override
		public CacheResolver cacheResolver() {
			return null;
		}

		@Override
		public KeyGenerator keyGenerator() {
			return (target, method, params) -> {
				//获取代理对象的最终目标对象
				StringBuilder sb = new StringBuilder();
				sb.append(target.getClass().getSimpleName()).append(":");
				sb.append(method.getName()).append(":");
				//调用SimpleKey的key生成器
				Object key = SimpleKeyGenerator.generateKey(params);
				return sb.append(key);
			};
		}

		@Override
		public CacheErrorHandler errorHandler() {
			return null;
		}
	}

	@Bean
	RedisCacheConfiguration defaultRedisCacheConfiguration(CacheProperties cacheProperties, RedisSerializer<Object> redisValueSerializer) {
		CacheProperties.Redis redisProperties = cacheProperties.getRedis();
		RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();

		config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisValueSerializer));
		if (redisProperties.getTimeToLive() != null) {
			config = config.entryTtl(redisProperties.getTimeToLive());
		}
		if (redisProperties.getKeyPrefix() != null) {
			config = config.computePrefixWith(cacheName -> String.format("%s:%s:", redisProperties.getKeyPrefix(), cacheName));

		}
		if (!redisProperties.isCacheNullValues()) {
			config = config.disableCachingNullValues();
		}
		if (!redisProperties.isUseKeyPrefix()) {
			config = config.disableKeyPrefix();
		}
		return config;
	}

}
